/**
 * 
 */
package cn.com.gzheroli.util;

import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.docx4j.XmlUtils;
import org.docx4j.dml.chart.CTBarChart;
import org.docx4j.dml.chart.CTBarSer;
import org.docx4j.dml.chart.CTChartSpace;
import org.docx4j.dml.chart.CTNumDataSource;
import org.docx4j.dml.chart.CTNumVal;
import org.docx4j.dml.chart.CTPie3DChart;
import org.docx4j.dml.chart.CTPieChart;
import org.docx4j.dml.chart.CTPieSer;
import org.docx4j.dml.chart.CTStrVal;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.DrawingML.Chart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.P;
import org.docx4j.wml.PPr;
import org.docx4j.wml.R;
import org.docx4j.wml.STVerticalJc;
import org.docx4j.wml.Tbl;
import org.docx4j.wml.TblWidth;
import org.docx4j.wml.Tc;
import org.docx4j.wml.TcPr;
import org.docx4j.wml.Tr;

import cn.com.gzheroli.core.util.docx4j.Docx4jUtils;

/**  
* @类名: VariableReplace  
* @描述: TODO(这里用一句话描述这个类的作用)  
* @作者: 李长荣 lichang_20011@163.com  
* @日期: 2017年5月21日  上午8:17:31
*@version V1.0  
*    
*/
public class VariableReplace {
	public void createChart() throws Docx4JException{
		String resultFile =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/test1.docx";

		boolean save = true;
		String outputfilepath =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/test22.docx";

	WordprocessingMLPackage template = WordprocessingMLPackage.load(new File(resultFile));
	//String chartPartName="testChart";
	String chartPartName = "/word/charts/chart1.xml";
    Chart chart = (Chart) template.getParts().get(new PartName(chartPartName));
    @SuppressWarnings("deprecation")
	List<Object> objects = chart.getJaxbElement().getChart().getPlotArea()
            .getAreaChartOrArea3DChartOrLineChart();

    //update chart values in doc
    Map data=new HashMap();
    data.put("aa", 1);
    data.put("bb", 2);
    for (Object object : objects) {

        if (object instanceof CTBarChart) {

            List<CTBarSer> ctBarSers = ((CTBarChart) object).getSer();

            for (CTBarSer ctBarSer : ctBarSers) {

                List<CTNumVal> ctNumVals = ctBarSer.getVal().getNumRef().getNumCache().getPt();
                List<CTStrVal> ctStrVals = ctBarSer.getCat().getStrRef().getStrCache().getPt();

                while (data.size() < ctNumVals.size()) {
                    ctNumVals.remove(data.size());
                }

                while (data.size() < ctStrVals.size()) {
                    ctStrVals.remove(data.size());
                }

                while (data.size() > ctNumVals.size()) {
                   // CTNumVal numVal = new CTNumVal();
                    //ctNumVals.add(ctNumVals.size(), numVal);
                    CTNumVal numVal = new CTNumVal();
                    numVal.setIdx(ctNumVals.size());
                    ctNumVals.add(ctNumVals.size(), numVal);
                }

                while (data.size() > ctStrVals.size()) {
                    //CTStrVal strVal = new CTStrVal();
                    //ctStrVals.add(ctStrVals.size(), strVal);
                    CTStrVal strVal = new CTStrVal();
                    strVal.setIdx(ctStrVals.size());
                    ctStrVals.add(ctStrVals.size(), strVal);
                }

                ctBarSer.getVal().getNumRef().getNumCache().getPtCount().setVal(data.size());
                ctBarSer.getCat().getStrRef().getStrCache().getPtCount().setVal(data.size());

                for (CTNumVal ctNumVal : ctNumVals) {
                    ctNumVal.setV("1");
                }

                for (CTStrVal ctStrVal : ctStrVals) {
                    ctStrVal.setV("aa");
                }
            }
        }
    }
    template.save(new File(resultFile));
}
	
	public void replaceTableAndVar() throws Docx4JException, JAXBException{
		Docx4jUtils docUtil=new Docx4jUtils();
		// Exclude context init from timing
		org.docx4j.wml.ObjectFactory foo = Context.getWmlObjectFactory();

		// Input docx has variables in it: ${colour}, ${icecream}
		String inputfilepath =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/test.docx";

		boolean save = true;
		String outputfilepath =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/test11.docx";

		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
				.load(new java.io.File(inputfilepath));
		MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

		HashMap<String, Object> mappings = new HashMap<String, Object>();
		mappings.put("colour", "green");
		mappings.put("估价对象", "chocolate");
		mappings.put("李长荣", "lichangrong李长荣");
		mappings.put("测试", "ceshi测试");
		long start = System.currentTimeMillis();

		// Approach 1 (from 3.0.0; faster if you haven't yet caused unmarshalling to occur):
			
			documentPart.variableReplace(mappings);
			List<Map<String,Object>> tblListMap=new ArrayList<Map<String,Object>>();
			Map<String,Object> repl1 = new HashMap<String, Object>();  
			repl1.put("估价对象", "function1");  
			repl1.put("用途", "desc1");  
			repl1.put("面积", "period1"); 
			
			repl1.put("估价单价", "period1"); 
			repl1.put("评估市场总值", "period1"); 
			repl1.put("估价师知悉的法定优先受偿款", "period1"); 
			repl1.put("抵押价值", "period1"); 
			  
			Map<String,Object> repl2 = new HashMap<String, Object>();  
			repl2.put("估价对象", "function1");  
			repl2.put("用途", "desc1");  
			repl2.put("面积", "period1"); 
			
			repl2.put("估价单价", "period1"); 
			repl2.put("评估市场总值", "period1"); 
			repl2.put("估价师知悉的法定优先受偿款", "period1"); 
			repl2.put("抵押价值", "period1");   
			  
			Map<String,Object> repl3 = new HashMap<String, Object>();  
			repl3.put("估价对象", "function1");  
			repl3.put("用途", "desc1");  
			repl3.put("面积", "period1"); 
			
			repl3.put("估价单价", "period1"); 
			repl3.put("评估市场总值", "period1"); 
			repl3.put("估价师知悉的法定优先受偿款", "period1"); 
			repl3.put("抵押价值", "period1"); 
			tblListMap.add(repl1);
			tblListMap.add(repl2);
			tblListMap.add(repl3);
			List<Tbl> tblList=docUtil.getAllTbl(wordMLPackage);
			for(Tbl tbl:tblList){	
				String tableTitle=tbl.getTblPr().getTblCaption().getVal();	
				//得到表格所有的行
				List<Tr> trList=docUtil.getTblAllTr(tbl);
				Tr templateRow = (Tr) trList.get(1); 
				List<Tc> tcList = docUtil.getTrAllCell(trList.get(1));
//				for(Tr tr:trList){
//					List<Tc> tcList = docUtil.getTrAllCell(tr);
//					for(Tc tc:tcList){
//						List<Object> objs=tc.getContent();
//						System.out.println(objs.get(0));
//					}
//				}
				int k=2;
				for (Map<String, Object> replacements : tblListMap) {  
		            // 2 and 3 are done in this method  
					docUtil.addRowToTable(tbl, templateRow, replacements,k);
					k=k+1;
		        }
				int colsNum=tcList.size();
				// 新增行
				for (int j = 0; j < 3; j++) {
					Tr tr = new Tr();
					tbl.getContent().add(tr);
					
					// 列
					for (int i = 0; i < colsNum; i++) {
						Tc tc = new Tc();
						tr.getContent().add(tc);
						Tc tcm=tcList.get(i);
						System.out.println(tcm.getContent().get(0));
						TcPr tcPr = new TcPr();
						TblWidth cellWidth = new TblWidth();
						cellWidth.setType("dxa");
						cellWidth.setW(BigInteger.valueOf(5));
						tcPr.setTcW(cellWidth);
						tc.setTcPr(tcPr);
						// 垂直居中
						docUtil.setTcVAlign(tc, STVerticalJc.CENTER);
						P p = new P();
						PPr pPr = new PPr();
						//pPr.setJc(jc);
						p.setPPr(pPr);
						R run = new R();
						p.getContent().add(run);
						tc.getContent().add(p);
					}
				}
				// 4. remove the template row  
		        tbl.getContent().remove(trList.get(1)); 
			}
			
/*		// Approach 2 (original)
		
			// unmarshallFromTemplate requires string input
			String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(), true);
			// Do it...
			Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
			// Inject result into docx
			documentPart.setJaxbElement((Document) obj);
*/
			
		long end = System.currentTimeMillis();
		long total = end - start;
		System.out.println("Time: " + total);

		// Save it
		if (save) {
			SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
			saver.save(outputfilepath);
		} else {
			System.out.println(XmlUtils.marshaltoString(documentPart.getJaxbElement(), true,
					true));
		}
	}
	/** 
     * 替换图表数据 
     */  
    public void replacePieChartData(WordprocessingMLPackage wordMLPackage, String[] chartArr) throws Docx4JException {  
        RelationshipsPart rp = wordMLPackage.getMainDocumentPart().getRelationshipsPart();  
        Relationship rel = rp.getRelationshipByType(Namespaces.SPREADSHEETML_CHART);  
        Chart chart = (Chart) rp.getPart(rel);  
        CTChartSpace chartSpace = chart.getContents();  
        List<Object> charObjList = chartSpace.getChart().getPlotArea().getAreaChartOrArea3DChartOrLineChart();  
        CTPieChart pieChart = (CTPieChart) charObjList.get(0);  
        List<CTPieSer> serList = pieChart.getSer();  
        CTNumDataSource serVal = serList.get(0).getVal();  
        List<CTNumVal> ptList = serVal.getNumRef().getNumCache().getPt();  
        ptList.get(0).setV(chartArr[0]);  
        ptList.get(1).setV(chartArr[1]);  
    }  
public static void main(String[] args) throws Exception {
//	String resultFile =  "/Users/lichangrong/docx4jword/test1.docx";
//	boolean save = true;
//	String outputfilepath =  "/Users/lichangrong/docx4jword/test22.docx";
//WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(resultFile));
//MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); 
////String chartPartName="testChart";
//String[] data=new String[]{"3","5"};
//	VariableReplace v=new VariableReplace();
//	v.replacePieChartData(wordMLPackage,data);
//	wordMLPackage.save(new File(outputfilepath)); 
	BigDecimal taskPoint = BigDecimal.valueOf(40.0).multiply(BigDecimal.valueOf(1.01*2)).add(BigDecimal.valueOf(6));
	System.out.println(taskPoint);
	// 任务分
	//v.createChart();
	}
}
